package com.gamer.p1.service;

import com.gamer.p1.dao.DataDao;
import com.gamer.p1.dao.UserDao;
import com.gamer.p1.dto.LoginReq;
import com.gamer.p1.dto.SaveReq;
import com.gamer.p1.entity.DataEntity;
import com.gamer.p1.entity.UserEntity;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author 种鑫
 * @date 2024/2/2 10:54
 */
@Service
public class DataService {
    @Resource
    DataDao dataDao;
    @Resource
    UserDao userDao;


    public UserEntity reg(LoginReq loginReq) {
        Optional<UserEntity> one = findUser(loginReq);
        if (one.isPresent()) {
            return null;
        } else {
            UserEntity userEntity = new UserEntity();
            BeanUtils.copyProperties(loginReq, userEntity);
            return userDao.save(userEntity);
        }
    }


    public Optional<UserEntity> findUser(LoginReq loginReq) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(loginReq, userEntity);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withIgnoreCase();

        Example<UserEntity> example = Example.of(userEntity, exampleMatcher);

        Optional<UserEntity> one = userDao.findOne(example);
        return one;
    }

    public DataEntity saveData(SaveReq saveReq) {
        DataEntity dataEntity = new DataEntity();

        BeanUtils.copyProperties(saveReq, dataEntity);
        DataEntity save = dataDao.save(dataEntity);
        return save;

    }

    public DataEntity loadData(String uid, String v, Long ts) {
        Optional<DataEntity> one = dataDao.findById(uid);
        return one.get();
    }

    public void delData(String uid) {
        dataDao.deleteById(uid);
    }
}
